package com.apexedu.portal.util.umail.httpclient;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;

/**
 * Created by luchen on 2015-12-23.
 */
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpUtil {
	public static String sslForString(File filePath, String key, String url, Map<String, String> paramMap, String charset) {
		String result = null;
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;
		try {
			KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
			FileInputStream instream = new FileInputStream(filePath);
			try {
				trustStore.load(instream, key.toCharArray());
			} catch (CertificateException e) {
				e.printStackTrace();
				try {
					instream.close();
				} catch (Exception localException) {
				}
			} finally {
				try {
					instream.close();
				} catch (Exception localException1) {
					localException1.printStackTrace();
				}
			}
			SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();

			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
			httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

			HttpGet httpget = new HttpGet(url);
			response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				result = EntityUtils.toString(entity, charset);
				EntityUtils.consume(entity);
			}
		} catch (ParseException e) {
			e.printStackTrace();
			try {
				if (response != null) {
					response.close();
				}
				if (httpclient != null)
					httpclient.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} catch (IOException e) {
			e.printStackTrace();
			try {
				if (response != null) {
					response.close();
				}
				if (httpclient != null)
					httpclient.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} catch (KeyManagementException e) {
			e.printStackTrace();
			try {
				if (response != null) {
					response.close();
				}
				if (httpclient != null)
					httpclient.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			try {
				if (response != null) {
					response.close();
				}
				if (httpclient != null)
					httpclient.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} catch (KeyStoreException e) {
			e.printStackTrace();
			try {
				if (response != null) {
					response.close();
				}
				if (httpclient != null)
					httpclient.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				if (httpclient != null)
					httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	public static void upload(String url, File filePath, String comment, ContentType commentContentType) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		try {
			HttpPost httppost = new HttpPost(url);
			FileBody fileBody = new FileBody(filePath);
			StringBody commentStringBody = new StringBody(comment, commentContentType);
			HttpEntity postEntity = MultipartEntityBuilder.create().addPart("file", fileBody).addPart("comment", commentStringBody).build();
			httppost.setEntity(postEntity);

			response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				System.out.println(entity.getContentLength());
				System.out.println(EntityUtils.toString(entity));
			}
			EntityUtils.consume(entity);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			try {
				response.close();
				httpclient.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} catch (IOException e) {
			e.printStackTrace();
			try {
				response.close();
				httpclient.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} finally {
			try {
				response.close();
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static void upload() {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceFile.action");

			FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));
			StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

			HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();

			httppost.setEntity(reqEntity);

			System.out.println("executing request " + httppost.getRequestLine());
			CloseableHttpResponse response = httpclient.execute(httppost);
			try {
				System.out.println("----------------------------------------");
				System.out.println(response.getStatusLine());
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					System.out.println("Response content length: " + resEntity.getContentLength());
				}
				EntityUtils.consume(resEntity);
			} finally {
				response.close();
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			try {
				httpclient.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} catch (IOException e) {
			e.printStackTrace();
			try {
				httpclient.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} finally {
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static String postForString(String url, Map<String, String> paramMap, String charset) {
		String result = null;
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;
		try {
			httpclient = HttpClients.createDefault();

			HttpPost httppost = new HttpPost(url);

			List paramList = new ArrayList();
			if ((paramMap != null) && (paramMap.size() > 0)) {
				Iterator it = paramMap.keySet().iterator();
				while (it.hasNext()) {
					String key = (String) it.next();
					String value = (String) paramMap.get(key);
					paramList.add(new BasicNameValuePair(key, value));
				}
			}
			UrlEncodedFormEntity uefe = new UrlEncodedFormEntity(paramList, charset);
			httppost.setEntity(uefe);
			System.out.println("executing request : " + httppost.getURI());

			response = httpclient.execute(httppost);

			HttpEntity entity = response.getEntity();
			if (entity != null)
				result = EntityUtils.toString(entity, charset);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			try {
				if (response != null) {
					response.close();
				}
				if (httpclient != null)
					httpclient.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
			try {
				if (response != null) {
					response.close();
				}
				if (httpclient != null)
					httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (IOException e) {
			e.printStackTrace();
			try {
				if (response != null) {
					response.close();
				}
				if (httpclient != null)
					httpclient.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				if (httpclient != null)
					httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	public static String postForString(String url, Map<String, String> paramMap) {
		return postForString(url, paramMap, "UTF-8");
	}

	public static String getForString(String url) {
		String result = null;
		CloseableHttpClient httpclient = null;
		CloseableHttpResponse response = null;
		try {
			httpclient = HttpClients.createDefault();

			HttpGet httpget = new HttpGet(url);
			System.out.println("executing request: " + httpget.getURI());

			response = httpclient.execute(httpget);

			HttpEntity entity = response.getEntity();
			if (entity != null) {
				result = EntityUtils.toString(entity);

				System.out.println(response.getStatusLine());

				System.out.println("Response content length: " + entity.getContentLength());
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			try {
				if (response != null) {
					response.close();
				}
				if (httpclient != null)
					httpclient.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} catch (ParseException e) {
			e.printStackTrace();
			try {
				if (response != null) {
					response.close();
				}
				if (httpclient != null)
					httpclient.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} catch (IOException e) {
			e.printStackTrace();
			try {
				if (response != null) {
					response.close();
				}
				if (httpclient != null)
					httpclient.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				if (httpclient != null)
					httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	public static String getForString(String url, Map<String, String> paramMap) {
		if ((paramMap != null) && (paramMap.size() > 0)) {
			StringBuffer sb = new StringBuffer();
			sb.append(url).append("?testStr=ok");
			Iterator it = paramMap.keySet().iterator();
			while (it.hasNext()) {
				String key = (String) it.next();
				String value = (String) paramMap.get(key);
				sb.append("&&").append(key).append("=").append(value);
			}
			url = sb.toString();
		}
		return getForString(url);
	}

	private static void sslTest() {
		File filePath = new File("d:\\tomcat.keystore");
		String key = "123456";
		String url = "https://localhost:8443/myDemo/Ajax/serivceJ.action";
		Map paramMap = null;
		String charset = "UTF-8";
		sslForString(filePath, key, url, paramMap, charset);
	}

	private static void postFormTest() {
		String url = "http://localhost:28080/shsgyjsxx_jw/jw/front/dormMgr";
		Map paramMap = new HashMap();
		paramMap.put("username", "yjyhj16898");
		paramMap.put("password", "yj123456");

		String result = postForString(url, paramMap);
		System.out.println("--------------------------------------");
		System.out.println("Response content : " + result);
		System.out.println("--------------------------------------");
	}

	private static void getTest() {
		String url = "http://www.baidu.com/";
		String result = getForString(url);
		System.out.println(result);
	}

	public static void main(String[] args) {
		postFormTest();
	}
}
